package com.yxhl.zoume.core.busticket.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.busticket.event.ZMArrivalStationEvent;
import com.yxhl.zoume.core.busticket.event.ZMStartStationEvent;
import com.yxhl.zoume.core.busticket.event.ZMTripDateEvent;
import com.yxhl.zoume.core.busticket.model.TicketsQueryOptions;
import com.yxhl.zoume.core.busticket.model.ZMSelectStartCityEntity;
import com.yxhl.zoume.core.busticket.presenter.BusTicketHomePresenter;
import com.yxhl.zoume.core.busticket.ui.info.ZMScheduleType;
import com.yxhl.zoume.core.busticket.view.BannerObtionView;
import com.yxhl.zoume.core.busticket.view.NetworkImageHolderView;
import com.yxhl.zoume.core.main.ui.MainActivity;
import com.yxhl.zoume.data.DataConstants;
import com.yxhl.zoume.data.http.model.splashbanner.BannerBean;
import com.yxhl.zoume.di.component.splash.DaggerSplashBannerComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by Xboy on 16/3/17.
 */
public class BusTicketHomeFragment extends BaseFragment implements BannerObtionView, OnItemClickListener {

    private static final String TAG = "BusTicketHomeFragment";

    // 顶部Banner
    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;

    // 出发城市
    @BindView(R.id.start_city_tv)
    TextView startCityTextView;

    // 到达城市
    @BindView(R.id.arrival_city_tv)
    TextView arrivalCityTextView;

    // 出行时间
    @BindView(R.id.trip_date_imageview)
    ImageView tripDateImageView;
    @BindView(R.id.trip_date_textview)
    TextView tripDateTextView;

    //出行时间箭头
    @BindView(R.id.trip_date_right_arrow_imageview)
    ImageView tripDateRightArrowImageView;

    // 车票查询
    @BindView(R.id.ticket_query_button)
    Button ticketQueryButton;

    @Inject
    BusTicketHomePresenter busTicketHomePresenter;
    //  private BusTicketHomeComponent homeComponent;

    private ZMSelectStartCityEntity mSelectStarCityEntity = new ZMSelectStartCityEntity();

    private List<ZMScheduleType> mZMScheduleTypeList;
    private String mArrivalCityCode;

    // 轮播间隔
    private static final long AUTO_TURNING_TIME = 5000;
    List<String> networkImageURLs = new ArrayList<>();

    private List<BannerBean> bannerList;
    private boolean isBannerClick = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Event处理
        onRxBusEvent();
        processImageList();
        // 绑定view
        busTicketHomePresenter.attachView(this);
        busTicketHomePresenter.obtainBanner(convenientBanner);
    }

    private void processImageList() {
        String[] images = {DataConstants.BUS_TICKET_HOME_BANNER_1, DataConstants.BUS_TICKET_HOME_BANNER_2};
        for (int i = 0; i < images.length; i++) {
            networkImageURLs.add(images[i]);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initDisplayData();
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        showBannerImages();
        busTicketHomePresenter.onResume();
        convenientBanner.startTurning(AUTO_TURNING_TIME);
    }

    @Override
    public void onPause() {
        super.onPause();
        busTicketHomePresenter.onPause();
        convenientBanner.stopTurning();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        busTicketHomePresenter.onDestroy();
        getSubscription().unsubscribe();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_busticket_home;
    }

    @Override
    protected void setupToolBar() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).setToolbarTitle(getString(R.string.main_tab_name_bus));
            ((MainActivity) mActivity).setToolbarVisible(true);
        }
    }

    @Override
    protected void initializeInjector() {
//        homeComponent = DaggerBusTicketHomeComponent.show()
//                .activityModule(new ActivityModule(getActivity()))
//                .appComponent(getAppComponent())
//                .build();
//        homeComponent.inject(this);
        DaggerSplashBannerComponent
                .builder()
                .activityModule(new ActivityModule(mActivity))
                .appComponent(getAppComponent())
                .build()
                .inject(this);
    }


    private void initDisplayData() {

        // 展示轮播图
        //  busTicketHomePresenter.showBannerImages(convenientBanner);

        //显示默认出行时间
        String dateStr = TimeUtils.dateToString(new Date());
        tripDateTextView.setText(dateStr);
    }

    /**
     * 定义车站选中消息接受
     */
    private void onRxBusEvent() {
        final int[] array = new int[]{0, 1};
        // 出发城市
        getSubscription().add(toSubscription(ZMStartStationEvent.class,
                new Action1<ZMStartStationEvent>() {
                    @Override
                    public void call(ZMStartStationEvent zmStartStationEvent) {
                        String startCityName = zmStartStationEvent.getStartCityName();
                        String startCityCode = zmStartStationEvent.getStartCityCode();
                        List<ZMScheduleType> scheduleTypeList = zmStartStationEvent.getScheduleTypeList();

                        mSelectStarCityEntity.setStartCityName(startCityName);
                        mSelectStarCityEntity.setStartCityCode(startCityCode);
                        mSelectStarCityEntity.setZmScheduleTypeList(scheduleTypeList);

                        startCityTextView.setText(startCityName);
                        arrivalCityTextView.setText("");

                        // 设置查询按钮状态
                        enableQueryButton();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));

        // 到达城市
        getSubscription().add(toSubscription(ZMArrivalStationEvent.class,
                new Action1<ZMArrivalStationEvent>() {
                    @Override
                    public void call(ZMArrivalStationEvent zmArrivalStationEvent) {
                        mArrivalCityCode = zmArrivalStationEvent.getArrivalCityCode();
                        mZMScheduleTypeList = zmArrivalStationEvent.getScheduleTypeList();

                        String arrivalCityName = zmArrivalStationEvent.getArrivalCityName();
                        arrivalCityTextView.setText(arrivalCityName);

                        // 设置查询按钮状态
                        enableQueryButton();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));

        // 出行日期
        getSubscription().add(toSubscription(ZMTripDateEvent.class,
                new Action1<ZMTripDateEvent>() {
                    @Override
                    public void call(ZMTripDateEvent zmTripDateEvent) {
                        String tripDate = zmTripDateEvent.getTripDate();
                        tripDateTextView.setText(tripDate);

                        // 设置查询按钮状态
                        enableQueryButton();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));
    }


    /**
     * 选择出发城市
     */
    @OnClick(R.id.start_city_tv)
    void onStartCityClick() {
        getAppComponent().navigator().navigateToStationsList(mActivity, null);
    }

    /**
     * 选择到达城市
     */
    @OnClick(R.id.arrival_city_tv)
    void onArrivalCityClick() {
        String startCityNameStr = startCityTextView.getText().toString().trim();
        if (!TextUtils.isEmpty(startCityNameStr)) {
            getAppComponent().navigator().navigateToStationsList(mActivity, mSelectStarCityEntity);
        } else {
            new MaterialDialog.Builder(mActivity)
                    .title(R.string.dialog_title_hint)
                    .content("请先选择出发城市")
                    .positiveText(R.string.dialog_confirm)
                    .positiveColorRes(R.color.app_primary_blue)
                    .canceledOnTouchOutside(false)
                    .show();
        }
    }

    /**
     * 选择出行时间
     */
    @OnClick(R.id.trip_date_textview)
    void onTripDateClick() {
        getAppComponent().navigator().navigateToCalendar(mActivity);
    }

    /**
     * 车票查询
     */
    @OnClick(R.id.ticket_query_button)
    void onQueryButtonClick() {
        String tripDate = tripDateTextView.getText().toString().trim();
        String startCityName = startCityTextView.getText().toString().trim();
        String arrivalCityName = arrivalCityTextView.getText().toString().trim();

        TicketsQueryOptions options = new TicketsQueryOptions(
                mSelectStarCityEntity.getStartCityCode(),
                startCityName,
                tripDate,
                arrivalCityName,
                mArrivalCityCode,
                mZMScheduleTypeList);
        getAppComponent().navigator().navigateToBusServicesList(mActivity, options);
    }

    /**
     * 设置查询按钮的可点击状态
     */
    private void enableQueryButton() {
        String arrivalCity = arrivalCityTextView.getText().toString();
        String tripDate = tripDateTextView.getText().toString();

        boolean enable = !TextUtils.isEmpty(arrivalCity) && !TextUtils.isEmpty(tripDate);
        ticketQueryButton.setEnabled(enable);
    }


    @Override
    public void renderBannerOnSuccess(List<BannerBean> bannerList) {
        this.bannerList = bannerList;
        isBannerClick = true;
        networkImageURLs.clear();
        for (BannerBean bannerbean : bannerList) {
            networkImageURLs.add(bannerbean.getImgUrl());
        }
        showBannerImages();
    }

    @Override
    public void renderBannerOnFailure(String failureMsg) {
        showBannerImages();
    }

    @Override
    public void renderBannerOnError(String errorMsg) {
        showBannerImages();
    }

    /**
     * 展示Banner轮播图
     */
    public void showBannerImages() {
        networkImageURLs.size();
        if (null == convenientBanner) {
            return;
        }
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImageURLs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                .setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(int position) {
        if (isBannerClick) {
            if (null != bannerList) {
                String targetUrl = bannerList.get(position).getTargetUrl();
                if (!TextUtils.isEmpty(targetUrl)) {
                    getAppComponent().navigator().navigateToAdActivity(mActivity, targetUrl );
                }
            }
        }
    }
}
